<!--
 * @author wangpeizhi
 -->
<template>
  <div id="sysconfig">
    <div v-show="searchshow" class="sysconfig-search">
      <el-collapse-transition>
        <div v-show="searchshow" class="course-search merge">
          <span class="svg-container">
            <svg-icon icon-class="search" />
          </span>
          <el-input v-model.trim="listQuery.searchContent" placeholder="请输入系统名称/配置名搜索" class="search-input" />
          <div class="course-search-btn">
            <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
            <span class="course-search-more" @click="searchshow = !searchshow">
              更多筛选条件
              <i class="el-icon-arrow-down" />
            </span>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">系统名称</div>
                <el-input v-model.trim="search.systemCode" style="width: 80%" class="filter-item" placeholder="请输入系统名称搜索" />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">配置名</div>
                <el-input v-model.trim="search.configName" style="width: 80%" class="filter-item" placeholder="请输入配置名称搜索" />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>

    <div class="btn-container">
      <div class="btn-container-title">
        <span>系统配置管理</span>
      </div>
      <div class="btn-container-btns">
        <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建配置</el-button> -->
      </div>
    </div>
    <div class="table">
      <my-table :list="list" tag="systemconfig" operationwidth="80" :list-loading="listLoading" :selection="false">
        <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </my-table>
    </div>
    <div class="btn-pagion fix">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" center width="800px">
      <el-form ref="dataForm" :model="temp" :rules="rules" class="dataForm" label-position="right" label-width="120px" style="height:450px">
        <!--<el-form-item label="系统名称" prop="systemCode">
          <el-select v-model="temp.systemCode" :disabled="true" style="width: 100%;">
            <el-option v-for="(item) in dict.XTMC" :key="item.dictValue" :value="item.dictValue" :label="item.dictName" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="配置名" prop="configName">
          <el-input v-model="temp.configName" :disabled="true" placeholder="请输入配置名" />
        </el-form-item>
        <el-form-item label="配置分类" prop="configCate">
          <el-radio-group v-model="temp.configCate">
            <el-radio v-for="v in dict.XTPZFL" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="temp.configCate=='XTPZFL02'" label="文件类型">
          <el-radio-group v-model="temp.configFileType">
            <el-radio label="XTPZWJLX001">图片</el-radio>
            <el-radio label="XTPZWJLX002">其他</el-radio>
          </el-radio-group>
          <div v-if=" temp.configName=='SYS_BACKEND_LOGO' ">
            <el-upload ref="up" class="avatar-uploader" :action="fileUrl" :on-change="imgPreview" :auto-upload="false" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="upHeaders" :data="upData">
              <img v-if="imageUrl" :src="imageUrl" class="imgavatar" />
              <i v-else class="avatar avatar-uploader-icon" />
              <p style="text-align:left;color:red;margin:0;padding:0;">建议上传尺寸为：384px*44px</p>
            </el-upload>
          </div>
          <div v-if=" temp.configName!='SYS_BACKEND_LOGO' && temp.configFileType =='XTPZWJLX001'">
            <el-upload ref="up" class="avatar-uploader" :on-change="imgPreview" :auto-upload="false" :action="fileUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="upHeaders" :data="upData">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </div>
          <div v-if=" temp.configName!='SYS_BACKEND_LOGO' && temp.configFileType =='XTPZWJLX002'">
            <el-upload ref="up" class="avatar-uploader" :action="fileUrl" :show-file-list="true" :file-list="fileList" :auto-upload="false" :on-preview="downFile" :on-change="filePreview" :before-upload="fileBef" :on-success="fileSucc" :headers="upHeaders" :data="upData">
              <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
              <div v-if="fileList.length>0" slot="tip" class="el-upload__tip">点击文件名称下载文件</div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="配置说明" prop="configRemark">
          <el-input v-model="temp.configRemark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入配置说明" />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <el-input v-model="temp.configValue" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入配置值" />
        </el-form-item>
        <el-form-item label="排序号" prop="configSort">
          <el-input v-model="temp.configSort" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="状态" prop="configState">
          <el-radio-group v-model="temp.configState">
            <el-radio v-for="v in dict.ZT" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sysmanageList, updateSysconfig, insertSysconfig, deleteSysconfig, getSysconfig, getDictByCode, downImg } from '@/views/systemconfig/api/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import MyTable from '@/components/Table'
import {
  getToken
} from '@/utils/auth'
export default {
  name: 'Sysconfig',
  components: { Pagination, MyTable },
  directives: { permission, elDragDialog },
  data() {
    return {
      searchshow: true,
      fileList: [],
      listQuery: {
        page: 1,
        limit: 10,
        searchContent: ''

      },
      search: {
        configName: '',
        systemCode: ''
      },
      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新增系统配置',
        update: '编辑系统配置'
      },
      listLoading: true,
      temp: {
      	id: '',
        systemCode: '',
        configName: '',
        configSort: '',
        configState: '',
        configRemark: '',
        configValue: '',
        configCate: '',
        configFileType: '',
				encryptionFlag: 0,
				viewFlag: 0
      },
      rules: {
        systemCode: [{ required: true, message: '请选择系统名称', trigger: 'blur' }],
        configName: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
        configCate: [{ required: true, message: '请选择配置分类', trigger: 'change' }],
        configSort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        configState: [{ required: true, message: '请选择配置状态', trigger: 'change' }],
        configValue: [{ required: true, message: '请输入配置值', trigger: 'blur' }],
        configRemark: [{ required: true, message: '请输入配置说明', trigger: 'blur' }]
      },
      dict: {
        XTMC: [], // 系统名称
        ZT: [], // 用户状态
        XTPZFL: []// 系统配置分类
      },
      imageUrl: '',
      fileUrl: '/API-ENTERPRISE-BACKEND/' + '/backend/sys/sysConfig/fileUpload',
      upData: { id: '' },
      upHeaders: { ttsxyhcs: '' }
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getList()
  },
  methods: {
    imgPreview(file, fileList) {
      const fileName = file.name
      const regex = /(.jpg|.jpeg|.png)$/
      if (regex.test(fileName.toLowerCase())) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.temp.configValue = file.name
      } else {
        this.$message.error('请选择图片文件')
      }
    },
    filePreview(file, fileList) {
      this.$refs.up.clearFiles()
      this.fileList = []
      this.fileList.push({ name: file.name, url: '' })
      this.temp.configValue = file.name
    },
    downFile(file) {
      downImg({ id: this.temp.id }).then(res => {
        const blob = new Blob([res.data])
        this.downLoadFile(file.name, blob)
      }).catch(() => {
        this.$message.error('请求失败')
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.code === '200') {
        this.$message.success('上传成功')
        this.imageUrl = URL.createObjectURL(file.raw)
        this.temp.configValue = file.name
        if (this.temp.configName == 'SYS_BACKEND_LOGO') {
          this.$store.commit('changeImg', this.imageUrl)
        }
      } else {
        this.$message.error(res.data.msg)
      }
    },
    fileBef() {
      this.upData.id = this.temp.id
      this.upHeaders.ttsxyhcs = getToken()
      return true
    },
    fileSucc(res, file) {
      if (res.code === '200') {
        this.$message.success('上传成功')
        this.$refs.up.clearFiles()
        this.fileList = []
        this.fileList.push({ name: file.name, url: '' })
        this.temp.configValue = file.name
      } else {
        this.$message.error(res.data.msg)
      }
    },
    downLoadFile(fileName, blob) {
      // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
      // IE10以上支持blob但是依然不支持download
      if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
        const link = document.createElement('a')// 创建a标签
        link.download = fileName// a标签添加属性
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        document.body.appendChild(link)
        link.click()// 执行下载
        URL.revokeObjectURL(link.href) // 释放url
        document.body.removeChild(link)// 释放标签
      } else { // 其他浏览器
        navigator.msSaveBlob(blob, fileName)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      let type = true
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传的图片只能是 JPG,PNG 格式!')
        type = false
      }
      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过 2MB!')
      }
      this.upData.id = this.temp.id
      this.upHeaders.ttsxyhcs = getToken()
      return type && isLt2M
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 查询列表
     */
    getList(obj) {
      const _this = this
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      if (this.searchshow) {
        query['searchContent'] = this.listQuery.searchContent
      } else {
        query['configName'] = this.search.configName
        query['systemCode'] = this.search.systemCode
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        sysmanageList(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          _this.listLoading = false
        }).catch(error => {
          reject(error)
          _this.listLoading = false
        })
      })
    },
    resetTemp() {
      this.temp = {
      	id: '',
        systemCode: '',
        configName: '',
        configSort: '',
        configState: '',
        configRemark: '',
        configValue: '',
        configFileType: '',
				encryptionFlag: 0,
				viewFlag: 0
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.listQuery.searchContent = ''
      this.listQuery.page = 1
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      if (row.id) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          getSysconfig({ id: row.id }).then((res) => {
            loading.close()
            for(let i in this.temp) {
            	if(res.data.data[i])
							this.temp[i] = res.data.data[i]
            }
            this.temp.configFileType == '' ? this.temp.configFileType = 'XTPZWJLX001' : this.temp.configFileType
            this.fileList = []

            if (this.temp.configCate === 'XTPZFL02' && this.temp.configFileType == 'XTPZWJLX001') {
              this.getImg()
            } else if (this.temp.configFileType == 'XTPZWJLX002') {
              this.imageUrl = ''
              this.setFile()
            }
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      } else {
        this.$message({
          message: '获取数据失败！',
          type: 'warning'
        })
      }
    },
    setFile() {
      this.fileList.push({ name: this.temp.configValue, url: '' })
    },
    getImg() {
      downImg({ id: this.temp.id }).then(res => {
        console.log('图片', res)
        const blob = new Blob([res.data], { type: 'image/jpg' })
        this.imageUrl = window.URL.createObjectURL(blob)
      }).catch(() => {
        this.$message.error('请求失败')
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row.id)
      }).catch(() => { })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          return new Promise((resolve, reject) => {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            insertSysconfig(this.temp).then(response => {
              this.dialogFormVisible = false
              loading.close()
              this.getList()

              this.$message({
                message: '创建成功',
                type: 'success'
              })
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }
      })
    },
    updateData() {
			if(this.temp.configValue === '关键参数，配置值不可见') {
				this.$message({
					message: '请填写正确的系统配置值',
					type: 'error'
				})
        return
			}
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          return new Promise((resolve, reject) => {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            delete tempData.configFile
            updateSysconfig(tempData).then(response => {
              this.dialogFormVisible = false
              loading.close()
              this.getList()
              this.$refs.up.submit()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }
      })
    },
    deleteData(ids) {
      return new Promise((resolve, reject) => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        deleteSysconfig({ ids: ids }).then(() => {
          loading.close()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
@import '@/styles/mixin.scss';
#sysconfig {
  padding: 10px;
  .avatar-uploader .el-upload {
    margin-bottom: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload__tip {
    margin-top: 0;
  }
  .avatar-uploader .el-upload {
    margin-bottom: 0;
    border: none;
  }
  .noImg {
    margin-left: 80px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .imgavatar {
    width: 380px;
    height: 90px;
    display: block;
  }
  .avatar {
    height: 200px;
    width: 200px;
  }

  .sysconfig-search {
    background-color: #fff;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 78%;
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 50%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    .btn-container-title {
      flex: 1;
      height: 46px;
      line-height: 46px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>

